import { Modal } from "antd";
import React, {useState, useEffect, useRef} from "react";
import Draggable from 'react-draggable';
/**
 * 公共弹窗组件
 */
export const CommonModal = props => {
	const { title, children, centered = true, className, noPadding, maxHeight = '65vh', minHeight = '200px', overflowX = 'hidden',  ...args } = props;
	const [disabled, setDisabled] = useState(true);
  const [bounds, setBounds] = useState({ left: 0, top: 0, bottom: 0, right: 0 });
  const draggleRef = useRef(null);

	const [index, setIndex] = useState();
	useEffect(() => {
		if(index || index == 0) {
			return;
		}
		const arr = document.getElementsByClassName('views-layout');
		for(let i in arr) {
			if(arr[i].style?.cssText.includes('display: block;')) {
				setIndex(i);
				break;
			}
		}
	}, [])


  const onStart = (_event, uiData) => {
    const { clientWidth, clientHeight } = window.document.documentElement;
    const targetRect = draggleRef.current?.getBoundingClientRect();
    if (!targetRect) {
      return;
    }
    setBounds({
      left: -targetRect.left + uiData.x + 72,
      right: clientWidth - (targetRect.right - uiData.x),
      top: -targetRect.top + uiData.y + 64,
      bottom: clientHeight - (targetRect.bottom - uiData.y),
    });
  };
	
	return (
		<Modal
			className={className}
			maskClosable={false}
            zIndex={900}
			getContainer={() => document.getElementsByClassName('views-layout')[index] || false}
			title={
				<div
					style={{
						width: '100%',
						cursor: 'move',
					}}
					onMouseOver={() => {
						if (disabled) {
							setDisabled(false);
						}
					}}
					onMouseOut={() => {
						setDisabled(true);
					}}
					onFocus={() => {}}
					onBlur={() => {}}
				>
					 {title}
				</div>
			}
			centered
			{...args}
			modalRender={(modal) => (
				<Draggable
					disabled={disabled}
					bounds={bounds}
					nodeRef={draggleRef}
					onStart={(event, uiData) => onStart(event, uiData)}
				>
					<div ref={draggleRef}>{modal}</div>
				</Draggable>
			)}
		>
			<div key={index} style={{ maxHeight, minHeight, overflowY: 'auto', overflowX, paddingBottom: noPadding ? 0 : '16px' }}>{children}</div>
		</Modal>
	);
};
export default CommonModal;
